<!--
 * @Description:
 * @Autor: 刘诗文
 * @Date: 2020-12-23 10:46:18
 * @LastEditors: 马毅
 * @LastEditTime: 2021-04-26 16:47:57
-->
<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="130" :formType="type" :isSubmitBtn="false" />
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <AjaxButton type="primary" v-if="this.type != 'show'" :click="save">保 存</AjaxButton>
      <el-button @click="close">取消</el-button>
    </div>
    <BaseDialog :visible.sync="actions.visible" :title="actions.title" destroyOnClose width="70%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <queryVehicleModel :formData="this.resData" @close="closeDialog" @vehicleData="vehicleData" />
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { phoneCus, phoneAndSolidifyCus } from '@/utils/validate';
import { getProvince, getCitys, getDistrict, getPostCode } from '@/api/customerRepair/customerInfo/ownerVehicleManagement';
import { saveKeyInfoChange, getKeyInfoChangeList } from '@/api/customerRepair/vehicleOwnerManagement/vehicleChange';
import queryVehicleModel from './queryVehicleModel';
import { notifyAction, isFormEmpty } from '../../../../utils';
import { isValidateDoubleForFeesSettlement } from '../../../../utils/validate';

export default {
  name: 'addKeyInfoChangePanel',
  mixins: [dictionary],
  components: {
    queryVehicleModel
  },
  props: {
    type: {
      type: String
    },
    formData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.selectedData = null;
    this.resData = {};
    return {
      formList: this.createFromList(),
      actions: { title: '', visible: false, type: '' }
    };
  },
  mounted() {
    this.getProvine();
    this.initialHandle();
  },
  methods: {
    createFromList() {
      return [
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          readonly: true,
          disabled: this.type === 'add' ? false : true,
          initialValue: '',
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.openVehicle}></el-button>;
          }
        },
        {
          type: 'SELECT',
          label: '客户性质',
          fieldName: 'ownerProperty',
          itemList: this.createDictList(8011),
          disabled: this.type === 'show' ? true : false,
          rules: [{ required: true, message: '请选择客户性质', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '客户编号',
          fieldName: 'ownerNo',
          disabled: true,
          rules: [{ required: true, message: '请输入客户编号', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '车主姓名',
          fieldName: 'ownerName',
          disabled: this.type === 'show' ? true : false,
          rules: [{ required: true, message: '请输入车主姓名', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '性别',
          fieldName: 'gender',
          itemList: this.createDictList(8012),
          disabled: true
          // rules: [{ required: true, message: '请选择性别', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '车主电话',
          fieldName: 'phone',
          disabled: this.type === 'show' ? true : false
          // rules: [
          //   {
          //     required: true,
          //     validator: (rule, value, callback) => {
          //       const message = '车主电话';
          //       phoneAndSolidifyCus(rule, value, callback, message);
          //     },
          //     trigger: 'blur'
          //   }
          // ]
        },
        {
          type: 'INPUT',
          label: '车主手机',
          fieldName: 'mobile',
          disabled: this.type === 'show' ? true : false
          // rules: [
          //   {
          //     required: true,
          //     validator: (rule, value, callback) => {
          //       const message = '车主手机';
          //       phoneCus(rule, value, callback, message);
          //     },
          //     trigger: 'blur'
          //   }
          // ]
        },
        {
          type: 'SELECT',
          label: '证件类型',
          fieldName: 'ctCode',
          initialValue: 80131001,
          disabled: true,
          itemList: this.createDictList('8013')
          // rules: [{ required: true, message: '请选择证件类型', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '证件号码',
          fieldName: 'certificateNo',
          disabled: true
          // rules: [{ required: true, message: '请填写证件号码', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '所在省份',
          fieldName: 'province',
          itemList: [],
          change: val => {
            this.provinceChange(val);
            let itemList = this.formList.find(item => item.fieldName === 'province').itemList;
            // this.resetAddress(val || '', itemList);
          },
          disabled: true
          // rules: [{ required: true, message: '请选择所在省份', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '城市',
          fieldName: 'city',
          itemList: [],
          change: val => {
            this.cityChange(val);
            let itemList = this.formList.find(item => item.fieldName === 'city').itemList;
            // this.resetAddress(val || '', itemList);
          },
          disabled: true
          // rules: [{ required: true, message: '请选择城市', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '区县',
          fieldName: 'district',
          itemList: [],
          change: val => {
            let itemList = this.formList.find(item => item.fieldName === 'district').itemList;
            // this.resetAddress(val || '', itemList);
          },
          disabled: true
          // rules: [{ required: true, message: '请选择区县', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '详细地址',
          fieldName: 'address',
          disabled: true,
          selfCols: 3
          // rules: [{ required: true, message: '请输入地址', trigger: 'blur' }]
        },
        {
          type: 'UPLOAD_FILE',
          label: '身份证附件',
          fieldName: 'identityUpload',
          upload: {
            actionUrl: '/api/file/oss/upload', //上传的地址
            fileTypes: ['pdf', 'jpg', 'png', 'bmp', 'pdf', 'doc', 'docx'],
            max: 1024 * 100,
            limit: 2
          },
          initialValue: '',
          disabled: false,
          selfCols: 2
          // rules: [{ required: true, message: '请上传身份证附件', trigger: 'blur' }]
        },
        {
          type: 'UPLOAD_FILE',
          label: '行驶证附件',
          fieldName: 'drivingFileUpload',
          upload: {
            actionUrl: '/api/file/oss/upload', //上传的地址
            fileTypes: ['pdf', 'jpg', 'png', 'bmp', 'pdf', 'doc', 'docx'],
            max: 1024 * 100,
            limit: 2
          },
          initialValue: '',
          disabled: false,
          selfCols: 2
          // rules: [{ required: true, message: '请上传行驶证附件', trigger: 'blur' }]
        }
      ];
    },
    async initialHandle() {
      if (this.type != 'add') {
        const res = await getKeyInfoChangeList({ currentPage: 1, pageSize: 20, pageNum: 1, limit: 20, current: 1, size: 20, changeId: this.formData.changeId });
        if (res.resultCode === 200) {
          if (res.errMsg) {
            notifyAction(res.errMsg, 'error');
          } else {
            let result = res.data.rows[0];
            this.formList.forEach(x => {
              x.initialValue = result[x.fieldName];
              if (x.fieldName === 'ownerName') {
                x.initialValue = result['newOwnerName'];
              }
              if (x.fieldName === 'province') {
                this.provinceChange(x.initialValue);
              }
              if (x.fieldName === 'city') {
                this.cityChange(x.initialValue);
              }
              if (x.fieldName === 'identityUpload') {
                let files = [];
                let url = !isFormEmpty(result['idEnclosureUrl']) ? result['idEnclosureUrl'].split(',') : [];
                let name = !isFormEmpty(result['idEnclosureName']) ? result['idEnclosureName'].split(',') : [];
                if (url !== [] && name !== []) {
                  for (let i = 0; i < url.length; i++) {
                    if (i <= name.length) {
                      files.push({ url: url[i], name: name[i] });
                    }
                  }
                }
                x.initialValue = files;
              }
              if (x.fieldName === 'drivingFileUpload') {
                let files = [];
                let url = !isFormEmpty(result['drivingEnclosureUrl']) ? result['drivingEnclosureUrl'].split(',') : [];
                let name = !isFormEmpty(result['drivingEnclosureName']) ? result['drivingEnclosureName'].split(',') : [];
                if (url !== [] && name !== []) {
                  for (let i = 0; i < url.length; i++) {
                    if (i <= name.length) {
                      files.push({ url: url[i], name: name[i] });
                    }
                  }
                }
                x.initialValue = files;
              }
            });
          }
        }
      }
    },
    // 清空下拉框表当控件的值和下拉列表
    clearFormItem(item) {
      item.initialValue = undefined;
      item.itemList = [];
    },
    // 获取省
    async getProvine() {
      const res = await getProvince();
      this.formList.find(item => item.fieldName === 'province').itemList = res.data.map(x => ({ value: x.regionId, text: x.regionName }));
    },
    // 获取市
    async provinceChange(regionId) {
      this.clearFormItem(this.formList.find(item => item.fieldName === 'city'));
      this.clearFormItem(this.formList.find(item => item.fieldName === 'district'));
      if (!regionId) return;
      const res = await getCitys(regionId);
      this.formList.find(item => item.fieldName === 'city').itemList = res.data.map(x => ({ value: x.regionId, text: x.regionName }));
    },
    // 获取区县
    async cityChange(regionId) {
      this.clearFormItem(this.formList.find(item => item.fieldName === 'district'));
      if (!regionId) return;
      const res = await getDistrict(regionId);
      this.formList.find(item => item.fieldName === 'district').itemList = res.data.map(x => ({ value: x.regionId, text: x.regionName }));
    },
    // 拼接地址
    resetAddress(val, itemList) {
      console.log(itemList);
      let newVal = itemList.find(item => item.value === val).text;
      console.log(newVal);
      let addressItem = this.formList.find(item => item.fieldName === 'address');
      let address = `${addressItem.initialValue || ''}`; // initialValue可能是undefined
      console.log(`resetAddress : ${address}`);
      addressItem.initialValue = `${address}${address.indexOf(String(newVal)) === -1 ? String(newVal) : ''}`;
    },
    // 取原车主表单值通用方法
    findFormItem(fieldName) {
      return this.formList.find(x => x.fieldName === fieldName) || {};
    },
    // 打开选择底盘号界面
    openVehicle() {
      this.actions = { title: '选择客户信息', visible: true, type: 'choose' };
    },
    // 处理选择底盘号数据
    vehicleData(val) {
      this.formList.forEach(x => {
        x.initialValue = val[x.fieldName];
      });
      // 市
      if (val['city']) {
        this.provinceChange(this.findFormItem('province').initialValue);
        this.findFormItem('city').initialValue = val['city'];
      }
      // 区
      if (val['district']) {
        this.cityChange(val['city']);
        this.findFormItem('district').initialValue = val['district'];
      }
    },
    // 关闭选择客户界面
    closeDialog() {
      this.actions.visible = false;
    },
    // 保存接口
    async save() {
      const [err, data] = await this.$refs.formPanel.GET_FORM_DATA();
      if (err) return;
      if (this.type === 'edit') {
        data.changeId = this.formData.changeId;
      }
      const res = await saveKeyInfoChange({ ...data });
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'error');
        } else {
          notifyAction('车主关键信息变更成功！');
        }
        this.$emit('close', true);
      }
    },
    // 关闭新增界面
    close() {
      this.$emit('close', false);
    }
  }
};
</script>
<style lang="less" scoped></style>
